package main.java.com.web;


import main.java.com.entity.User;
import main.java.com.service.LoginFrontService;
import main.java.com.service.impl.LoginFrontServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

/**
 * 前台登录
 */
@WebServlet("/loginFront")
public class LoginFrontServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");
        String phone = req.getParameter("phone");
        String verificationCode = req.getParameter("verificationCode");
        //用户输入发手机号码，查询是否存在
        LoginFrontService loginFrontService = new LoginFrontServiceImpl();
        List<User> list = loginFrontService.login(phone);
        if (!verificationCode.equals(Verification())) {
            req.setAttribute("msg", "输入验证码不正确");
            req.getRequestDispatcher("/front/login.jsp").forward(req, resp);
            return;
        }

        if (list.size() == 0) {
            //添加
            int result = loginFrontService.addUser(phone);
            if (result == 1) {
                req.setAttribute("msg", "手机号注册成功");
            }
        }
        list = loginFrontService.login(phone);
        //过滤器拦截
        HttpSession session = req.getSession();
        session.setAttribute("qtuser", phone);
        req.getSession().setAttribute("list", list);
        req.getRequestDispatcher("/front/index.jsp").forward(req, resp);

    }

    /**
     * 生成验证码的方法
     *
     * @return
     */
    public String Verification() {
        //随机数
        int num = 1234;
        return num + "";
    }
}
